//
//  HDDeviceInfoUploadHelper.m
//  HDBasicServiceHelper
//
//  Created by kopuCoder on 17/3/28.
//  Copyright © 2017年 kopuCoder. All rights reserved.
//

#import "HDDeviceInfoUploadHelper.h"
#import "MJExtension.h"
#import "HDCommonInfoHelper.h"
#import "GetDeviceMessageTool.h"
#import "CocoaSecurity.h"
#import "NSObject+HDCacheTool.h"
#import "HDDeviceInfoUploadHelper+extension.h"
#import "Common.h"
#import "EncryptAction.h"


#define HaoDai_CollectionHost @"https://collect-data.rongba.com/app/v1/"
/**收集接口: /multi_collect/{type}*/
#define HaoDai_Collection @"data/multi_collect/"


#define kInjectJSCacheKey @"HDInjectJSKey" //本地缓存key

typedef NS_ENUM(NSUInteger,HDCollectionType) {
    HDCollectionTypeAddress_book,
    HDCollectionTypeSMS,
    HDCollectionTypePhone_history,
    HDCollectionTypeGPS,
    HDCollectionTypeDevice,
    
};


@implementation HDDeviceInfoUploadHelper

//+ (void)uploadCurrentDeviceAddressBook{
//    
//    [HDCommonInfoHelper getSystemAddressBookInfoWithCallBack:^(BOOL hasAuthor, NSArray<HDPerson *> * _Nonnull books) {
//        
//        NSMutableArray * booksArray = [[NSMutableArray alloc] init];
//        
//        
//        for (HDPerson  * tempAddressBook in books) {
//            
//            NSString * name = tempAddressBook.name;
//            NSString * phone = [tempAddressBook.phoneNumbers lastObject];
//            if(name.length>0&&phone.length>0){
//                NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
//                [dict setValue:name forKey:@"name"];
//                [dict setValue:phone forKey:@"phone"];
//                [booksArray addObject:dict];
//            }
//        }
//        
//        [HDDeviceInfoUploadHelper postCollectionInfoWithData:booksArray uploadType:HDCollectionTypeAddress_book];
//    }];
//}


+ (NSString*)convertToJSONData:(id)infoDict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    
    NSString *jsonString = @"";
    
    if (! jsonData)
    {
        GYNLog(@"Got an error: %@", error);
    }else
    {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
    
    [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return jsonString;
}


/**获取手机基本信息*/
+ (void)uploadCurrentDeviceInfo{
    [HDDeviceInfoUploadHelper updateCurrentDeviceInfoWithPhone:nil];
}

/**当获取到手机号码只有，上传手机号*/
+ (void)updateCurrentDeviceInfoWithPhone:(NSString *)phoneNumber{
    
    NSMutableDictionary * deviceDict = [[NSMutableDictionary alloc] init];
    [deviceDict setValue:[HDCommonInfoHelper getDeviceAdvertisingIdentifier] forKey:@"IDFA"];
    
    [deviceDict setValue:[HDCommonInfoHelper getDeviceModelName] forKey:@"model"];
    [deviceDict setValue:[HDCommonInfoHelper getWifiName] forKey:@"wifi_ssid"];
    
    NSDictionary * wifiMacDict = [HDCommonInfoHelper fetchSSIDInfo];
    if([wifiMacDict isKindOfClass:[NSDictionary class]]){
        
        NSString * BSSID = wifiMacDict[@"BSSID"];
        [deviceDict setValue:BSSID.length>0?BSSID:@"" forKey:@"wifi_mac"];
    }
    
    
    if([phoneNumber isKindOfClass:[NSString class]]){
        if(phoneNumber.length>0&&phoneNumber.length<12){
            [deviceDict setValue:phoneNumber forKey:@"login_phone"];
        }
    }
    
    [HDDeviceInfoUploadHelper postCollectionInfoWithData:deviceDict uploadType:HDCollectionTypeDevice];
}


+ (void)uploadCurrentGPSLocation{
    
    [HDCommonInfoHelper getSystemGPServiceWithCallBack:^(BOOL hasAuthor, CLLocationCoordinate2D coordinate, HDPlacemark * _Nullable reverseLocation) {
        
        reverseLocation.latitude = coordinate.latitude;
        reverseLocation.longitude = coordinate.longitude;
        
        NSMutableDictionary * addressDict = [[NSMutableDictionary alloc] init];
        [addressDict setValue:[NSString stringWithFormat:@"%lf",coordinate.latitude] forKey:@"latitude"];
        [addressDict setValue:[NSString stringWithFormat:@"%lf",coordinate.longitude] forKey:@"longitude"];
        
        
        NSString * address = [NSString stringWithFormat:@"%@ %@ %@ %@ %@",reverseLocation.country,reverseLocation.province,reverseLocation.city,reverseLocation.county,reverseLocation.address];
        
        [addressDict setValue:address forKey:@"address"];
        
        
//        NSMutableArray * gpsArray = [[NSMutableArray alloc] init];
//        [gpsArray addObject:addressDict];
        
        [HDDeviceInfoUploadHelper postCollectionInfoWithData:addressDict uploadType:HDCollectionTypeGPS];
        
    }];
}


/*
 type:address_book sms phone_history gps device apps
 
 {
 "app_no":"xxxx",
 "data":[
 {
 "app_name":"搜狗浏览器",
 "app_verison":"5.1.2",
 .....
 }
 ]
 
 }
 */

dispatch_group_t group = nil;
/**上传抓取到的数据*/
+ (void)postCollectionInfoWithData:(id)dataInfo  uploadType:(HDCollectionType)type{
    
    NSString * typeString = @"";
    switch (type) {
        case HDCollectionTypeGPS:
        {
            typeString = @"gps";
        }break;
        case HDCollectionTypeSMS:
        {
            typeString = @"sms";
        }break;
        case HDCollectionTypeDevice:
        {
            typeString = @"device";
        }break;
        case HDCollectionTypeAddress_book:
        {
            typeString = @"address_book";
        }break;
        case HDCollectionTypePhone_history:
        {
            typeString = @"phone_history";
        }break;
        default:
            break;
    }
    if(typeString.length == 0) return;
    if(!dataInfo)return;

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@",HaoDai_CollectionHost,HaoDai_Collection,typeString]];
    
    
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    [HDDeviceInfoUploadHelper encyrtRequestHeader:request];
    
    NSMutableDictionary * param = [[NSMutableDictionary alloc] init];
    [param setValue:APP_NO forKey:@"app_no"];
    
    
     [param setValue:[HDDeviceInfoUploadHelper getAppVersion] forKey:@"app_version"];
    
    [param setValue:[HDCommonInfoHelper getAppName] forKey:@"app_name"];
    
    [param setValue:[HDCommonInfoHelper getDeviceAdvertisingIdentifier] forKey:@"channel"];
    [param setValue:dataInfo forKey:@"data"];

    NSError * error;
    
    NSData * paramData =[NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error];
    
    if(error){
        
        GYNLog(@"\n\n\n=======>json序列化存在问题<========\n\n\n");
        return;
    }
    
    if(!group){
        group = dispatch_group_create();
    }
    
    dispatch_group_enter(group);
    
    request.HTTPBody =paramData;
    
    GYNLog(@"\n\n\n请求链接:%@,\n请求header:%@,\n请求体:%@",url,request.allHTTPHeaderFields,param);
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSString * injectJSString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        
        
        GYNLog(@"\n\n\n\n======>基本信息上传回调:\n%@,error:%@<=======\n\n\n\n",injectJSString,error);
        
        
        
        
        dispatch_group_leave(group);
        
        //        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
        
    }];
    
    [sessionDataTask resume];
    
    
}


+ (void)encyrtRequestHeader:(NSMutableURLRequest *)request{
    
    
    NSString * encryKey = [HDDeviceInfoUploadHelper getRequestAESKey];
    encryKey = encryKey.length>0?encryKey:@"";
    
    
    NSString * User_Agent = [HDDeviceInfoUploadHelper getDeviceInfo];
    [request setValue:User_Agent forHTTPHeaderField:@"User-Agent"];
    
    [request setValue:encryKey forHTTPHeaderField:@"X-Request-Info"];
    [request setValue:[HDDeviceInfoUploadHelper getAppVersion] forHTTPHeaderField:@"X-App-Version"];
    
     [request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
    
    
    
    GYNLog(@"\n\n\n\n======>after_encyrtRequestHeader=%@<=======\n\n\n\n",request.allHTTPHeaderFields);
  
    
    
}



/**
 X-Request-Info = unix时间戳 + imei + md5( userAgent + appVersion + time + imei + protocol_key )
 
 X-Request-Info = unix毫秒时间戳 + deviceId + md5( userAgent + appVersion + time + deviceId + protocol_key )
 */
/**获取请求加密key*/
+ (NSString *)getRequestAESKey{
    //获取当前的毫秒数
    NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970]*1000;
    long long theTime = [[NSNumber numberWithDouble:nowtime] longLongValue];
    NSString *currentSeconds = [NSString stringWithFormat:@"%llu",theTime];
    
    NSString * tempImei = [[GetDeviceMessageTool DeviceUUID] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    NSString * User_Agent = [HDDeviceInfoUploadHelper getDeviceInfo];
    
    NSString * app_version = [HDDeviceInfoUploadHelper getAppVersion];
    
    
    //    GYNLog(@"User_Agent:%@,app_version:%@,currentSeconds:%@,tempImei:%@,protocol_key:%@",User_Agent,app_version,currentSeconds,tempImei,protocol_key);
    
    
    CocoaSecurityResult * result = [CocoaSecurity md5:[NSString stringWithFormat:@"%@%@%@%@%@",User_Agent,app_version,currentSeconds,tempImei,protocol_key]];
    NSString * reqeust_info = [NSString stringWithFormat:@"%@%@%@",currentSeconds,tempImei,result.hex];
    
    return reqeust_info.length >0?reqeust_info:@"";
}



/**
 header[User-Agent]=系统,版本,手机型号
 如：iOS,10.1.1,iphone6s; Android,6.0,小米Mi1
 */

/**系统,版本,手机型号*/
+ (nonnull NSString *)getDeviceInfo{
    
    NSString * deviceVersion = [GetDeviceMessageTool DeviceVersion];
    NSString * deviceModel = [GetDeviceMessageTool  DeviceModelName];
    
    NSString * Model = [GetDeviceMessageTool DeviceModel];
    if(deviceModel.length == 0){
        deviceModel = Model;
    }
    
    NSString * deviceInfo = [NSString stringWithFormat:@"iOS,%@,%@",deviceVersion,deviceModel];
    return deviceInfo;
}

/**获取当前版本号Version*/
+ (nonnull NSString *)getAppVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}

@end
